import React from 'react';
import { Form, Modal, InputNumber, Slider } from 'antd';
import moment from 'moment';
import LimitedTextArea from '../../../components/LimitedTextArea';
import { FileFormItem } from './components';
import { pauseTask, getPauseInfo } from '../../../services';
import { workTimeFormat } from '../../../utils';
import { FORM_DEFAULT_LAYOUT, MODAL_DEFAULT_PARAM, MODAL_FORCE_PARAM } from '../config';
import styles from './index.less';

const PauseActionModal = ({ form, taskId, visible, setVisible, onOk }) => {
    // console.log('PauseActionModal -> taskId', taskId);
    const { getFieldDecorator, validateFields } = form;
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const [auditName, setAuditName] = React.useState('');
    const [launchName, setLaunchName] = React.useState('');
    const [startTime, setStartTime] = React.useState('');
    const [usedTimeFormat, setUsedTimeFormat] = React.useState('0天0小时0分钟');
    const [taskProgress, setTaskProgress] = React.useState(0);
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            setConfirmLoading(true);
            // console.log(values);
            const {
                actualWorkDuration,
                taskProgress: progress,
                operateReason,
                files = { uploadResourceFile: '' }
            } = values;
            const { uploadResourceFile = '' } = files;
            // console.log(actualWorkDuration);
            // console.log(progress);
            // console.log(operateReason);
            // console.log(uploadResourceFile);
            pauseTask({
                taskId,
                actualWorkDuration: actualWorkDuration * 60,
                operateReason,
                taskProgress: progress,
                resourceRelation: uploadResourceFile ? [uploadResourceFile] : []
            })
                .then(res => {
                    const { code } = res;
                    if (code === 10000) {
                        if (onOk) onOk();
                        setVisible(false);
                    }
                })
                .finally(() => {
                    setConfirmLoading(false);
                });
        });
    };

    const getDetail = async () => {
        const res = await getPauseInfo(taskId);
        const { code, data } = res;
        // console.log(data);
        if (code === 10000) {
            const {
                auditEmployeeName,
                launchEmployeeName,
                actualStartTime,
                actualWorkDuration,
                taskProgress: progress
            } = data;
            if (auditEmployeeName) {
                setAuditName(auditEmployeeName);
            } else {
                setAuditName('');
            }
            if (launchEmployeeName) {
                setLaunchName(launchEmployeeName);
            } else {
                setLaunchName('');
            }
            if (actualStartTime) {
                setStartTime(
                    moment(actualStartTime).format(
                        actualStartTime.indexOf('00:00:00') !== -1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'
                    )
                );
            }
            setTaskProgress(progress || 0);
            form.setFieldsValue({
                taskProgress: progress || 0
            });
            if (actualWorkDuration) {
                form.setFieldsValue({
                    actualWorkDuration: actualWorkDuration / 60
                });
                setUsedTimeFormat(workTimeFormat(actualWorkDuration));
            }
        }
    };

    const handleTimeChange = val => {
        if (Number(val)) {
            setUsedTimeFormat(workTimeFormat(val * 60));
        } else {
            setUsedTimeFormat('0天0小时0分钟');
        }
    };

    const handleSliderChange = value => {
        setTaskProgress(value);
    };

    React.useEffect(() => {
        if (visible) {
            setAuditName('');
            setLaunchName('');
            setStartTime('');
            setUsedTimeFormat('0天0小时0分钟');
            setTaskProgress(0);
        }
        if (visible && taskId) {
            getDetail();
        }
    }, [visible]);

    return (
        <Modal
            {...MODAL_DEFAULT_PARAM}
            title="暂停"
            width={720}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            wrapClassName={styles.miniMarginBottom}
            onCancel={() => setVisible(false)}
            {...MODAL_FORCE_PARAM}
        >
            <Form {...FORM_DEFAULT_LAYOUT} labelCol={{ span: 6 }}>
                {auditName && <Form.Item label="温馨提示">确定后，需由审核人【{auditName}】通过后方可生效</Form.Item>}
                {!auditName && launchName && (
                    <Form.Item label="温馨提示">确定后，需由发起人【{launchName}】通过后方可生效</Form.Item>
                )}
                <Form.Item label="实际开始时间">{startTime}</Form.Item>
                <Form.Item label="已用工时">
                    {getFieldDecorator('actualWorkDuration', {
                        initialValue: '',
                        rules: [
                            {
                                required: true,
                                message: '请输入已用工时！'
                            }
                        ]
                    })(
                        <InputNumber
                            min={0}
                            max={9999.9}
                            precision={1}
                            placeholder="请输入已用工时"
                            formatter={value => `${value}`.replace('.0', '')}
                            style={{ width: 150, marginRight: 10 }}
                            onChange={handleTimeChange}
                        />
                    )}
                    小时（{usedTimeFormat}）
                </Form.Item>
                <Form.Item label="当前进度">
                    <span
                        style={{
                            position: 'absolute',
                            display: 'block',
                            width: 50,
                            left: 320,
                            color: '#585858'
                        }}
                    >
                        {taskProgress}%
                    </span>
                    {getFieldDecorator('taskProgress', {
                        initialValue: 0
                    })(<Slider onChange={handleSliderChange} style={{ width: 300 }} />)}
                </Form.Item>
                <Form.Item label="原因">
                    {getFieldDecorator('operateReason', {
                        rules: [
                            {
                                required: true,
                                message: '请输入原因'
                            }
                        ]
                    })(<LimitedTextArea placeholder="请输入原因" />)}
                </Form.Item>
                <FileFormItem form={form} />
            </Form>
        </Modal>
    );
};

export default Form.create()(PauseActionModal);
